package com.lzw.controller;

import com.lzw.bean.User;
import com.lzw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    /**
     * 用户登录
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestParam String userCode, @RequestParam String userPassword, HttpSession session, Model model) {
        User user = userService.login(userCode);
        System.out.println(user.toString());

        if (user != null) {
            if (user.getUserPassword().equals(userPassword)) {
                System.out.println("==============================");
                //登录成功
                session.setAttribute("userSession", user);
                return "jsp/frame";
            } else {
                System.out.println("===========faile==========");

                model.addAttribute("error", "登录失败");
                return "login";
            }
        } else {
            model.addAttribute("error", "你输入的用户名或密码有误");
            return "login";
        }
    }

    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpSession session) {
        User userSession = (User) session.getAttribute("userSession");
        if (userSession != null) {
            session.removeAttribute("userSession");
        }
        return "login";
    }
}
